package model.tokens;

import java.util.Queue;
import java.util.Stack;

import model.semantics.Node;

import model.parser.ParserException;

/**
 * Right parenthesis.
 */

public class RightGroupToken<T> extends Token<T> {

    public RightGroupToken(TokenConstructorArguments<T> args) {
        super(args);
    }

    @Override
    public void process(Automaton<T> state) {
        /*
         * Pop everything off the stack until we hit the left paren and add to
         * the state.output queue.
         */
        while (!state.operatorStack.empty()
                && !(state.operatorStack.peek() instanceof LeftGroupToken)) {
            state.output.add(((FunctionalToken<T>) state.operatorStack.pop())
                    .makeNewInstance(state.output));
        }

        /*
         * Remove the remaining left paren.
         */
        if (state.operatorStack.empty())
            throw ParserException.UNMATCHED_PAREN;
        state.operatorStack.pop();

        if (!state.operatorStack.empty()
                && state.operatorStack.peek() instanceof FunctionToken) {
            ((FunctionalToken<T>) state.operatorStack.pop())
                    .makeNewInstance(state.output);
        }
    }
}
